<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-col :span="10">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="英克码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bar">
                <a-input v-model="model.bar" placeholder="请输入英克码" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="UDI" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="udi">
                <a-input
                  style="width: 400px; z-index: 1000"
                  v-model.trim="model.udi"
                  placeholder="请输入UDI"
                  :disabled="formDisabled"
                  :allowClear="!formDisabled"
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" style="display: flex; justify-content: flex-end">
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-button v-if="!formDisabled" type="primary" @click="udiSplitFun">自动解析</a-button>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="产品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productName">
                <a-input v-model="model.productName" placeholder="请输入产品名称" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                label="生产厂家"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                prop="productYlqxzcrbarmc"
              >
                <a-input
                  v-model="model.productYlqxzcrbarmc"
                  placeholder="请输入生产厂家"
                  :disabled="formDisabled"
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="批号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="batch">
                <a-input v-model="model.batch" placeholder="请输入批号" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="12">
              <a-form-model-item
                label="最小标识"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                prop="flaproductZxxsdycpbsgC"
              >
                <a-input
                  v-model="model.productZxxsdycpbs"
                  placeholder="请输入最小标识"
                  :disabled="formDisabled"
                ></a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="12" v-if="show30">
              <a-form-model-item label="(30)标识" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flagC">
                <a-input v-model="model.flagC" placeholder="请输入(30)标识" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="show20">
              <a-form-model-item label="(20)标识" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flagD">
                <a-input v-model="model.flagD" placeholder="请输入(20)标识" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="序号91" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="serialNumberA">
                <a-input v-model="model.serialNumberA" placeholder="请输入序号91" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="序号21" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="serialNumberB">
                <a-input v-model="model.serialNumberB" placeholder="请输入序号21" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>

            <a-col :span="12">
              <a-form-model-item label="产品规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productSpec">
                <a-input v-model="model.productSpec" placeholder="请输入产品规格" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="注册证" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="zczbhhzbapzbh">
                <a-input v-model="model.zczbhhzbapzbh" placeholder="请输入注册证" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="生产日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="manufacture">
                <a-input v-model="model.manufacture" placeholder="请输入生产日期" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="有效期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="validity">
                <a-input v-model="model.validity" placeholder="请输入生产日期" :disabled="formDisabled"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="14">
          <a-col :span="24">
            <a-form-model-item label="实物图片" :labelCol="labelCol2" :wrapperCol="wrapperCol" prop="bar">
              <img
                style="width: 700px; height: 600px"
                class="fit-picture"
                :src="imgSrc"
                alt="暂无图片"
                :style="{ transform: `rotate(${rotation}deg)` }"
                @click="rotateImage"
              />
            </a-form-model-item>
          </a-col>
        </a-col>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { queryYkCodeDetail } from '@/api/warehouse'
export default {
  name: 'YkCodeForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      model: {},
      udiError: false,
      imgSrc: '',
      labelCol: {
        // 这是label的占比份数，span表示份
        xs: { span: 24 }, //这个就是当前分辨率小于576px时候运用的比例
        sm: { span: 8 }, //这个就是当前分辨率大于576px时候运用的比例
      },
      wrapperCol: {
        // 这个是输入框的占比份数
        xs: { span: 24 }, //这个就是当前分辨率小于576px时候运用的比例
        sm: { span: 16 }, //这个就是当前分辨率大于576px时候运用的比例
      },
      labelCol2: {
        xs: { span: 16 }, //这个就是当前分辨率小于576px时候运用的比例
        sm: { span: 4 }, //这个就是当前分辨率大于576px时候运用的比例
      },
      wrapperCol2: {
        xs: { span: 24 }, //这个就是当前分辨率小于576px时候运用的比例
        sm: { span: 18 }, //这个就是当前分辨率大于576px时候运用的比例
      },
      rotation: 0,
      confirmLoading: false,
      validatorRules: {
        udi: [{ required: true, type: 'string', message: '请填写UDI!' }],
        productName: [{ required: true, type: 'string', message: '请输入产品名称!' }],
        batch: [{ required: true, type: 'string', message: '请填写批号' }],
        productYlqxzcrbarmc: [{ required: true, type: 'string', message: '请填写生产厂家' }],
        productZxxsdycpbs: [{ required: true, type: 'string', message: '请填写最小标识(品码)' }],
        productSpec: [{ required: true, type: 'string', message: '请填写产品规格!' }],
        manufacture: [{ required: true, type: 'string', message: '请填写生产日期!' }],
        validity: [{ required: true, type: 'string', message: '请填写有效期' }],
      },
      isSubmit: true,
      errorText: '',
      url: {
        edit: '/wms/wmsBarBindOrderDetail/editBarInfo',
      },
      searchKey: null,
      columns: [
        {
          title: '规格',
          dataIndex: 'productSpec',
          key: 'productSpec',
          width: 120,
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          key: 'productName',
        },
        {
          title: '批次',
          dataIndex: 'batch',
          key: 'batch',
          width: 200,
        },
      ],
      notOneUdi: '',
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },

    show20() {
      let flag = false
      let udi = this.model.udi
      const hasMatch = /\((20)\)/.test(udi)
      if (hasMatch) {
        return (flag = true)
      }
      return flag
    },
    show30() {
      let flag = false
      let udi = this.model.udi
      const hasMatch = /\((30)\)/.test(udi)
      if (hasMatch) {
        return (flag = true)
      }
      return flag
    },
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    rotateImage() {
      this.rotation += 90 // 每次点击旋转 90 度
    },
    // 校验手机号
    validateUdi(rule, value, callback) {
      console.log(value)
      if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
        callback()
      } else {
        callback('您的手机号码格式不正确!')
      }
    },

    udiSplitFun(e) {
      let code = this.model.udi
      console.log(code)
      // 查看是否包含中文的 括号（）
      const containsChineseParentheses = /[（|）]/.test(code)
      // 检查一个字符串中是否包含空格
      const containsSpace = /\s/.test(code)

      if (containsChineseParentheses) {
        this.$message.warning('请输入英文格式的括号')
        this.errorText = '请输入英文格式的括号'
        this.isSubmit = false
        return
      }
      if (containsSpace) {
        this.$message.warning('请不要输入空格')
        this.errorText = '请不要输入空格'
        this.isSubmit = false
        return
      }
      if (code.charAt(0) == '(' && code.slice(0, 3) == '(01') {
        this.model.udi = code
        this.isSubmit = true
        this.udgeLegaludgeUdi(code)
      }
    },
    udgeLegaludgeUdi(code) {
      let arr = code.split('(')
      for (var i = 0; i < arr.length; i++) {
        let ele = arr[i]
        if (ele !== '') {
          // console.log('hhhh',ele2.substring(0,2))
          // return
          var flag2 = ele.substring(0, 2)
          console.log('flag2:' + flag2)
          if (flag2 === '01') {
            this.model.productZxxsdycpbs = ele.substring(3) // (01)后面的数字
            let oneStr = this.model.udi
            // 查找第二个括号的索引位置
            const secondParenIdx = oneStr.indexOf('(', oneStr.indexOf('(') + 1)
            if (secondParenIdx === -1) {
              console.log('不存在第二个括号')
              // this.isChangBar = true;
              // this.inquire()
            } else {
              console.log('存在第二个括号')
              const regex1 = /\((01)\)(.+?)\(/
              const match1 = oneStr.match(regex1)

              if (match1 && match1.length >= 3) {
                const string1 = `(${match1[1]})${match1[2]}`.trim()
                console.log('字符串1:', string1)
                // this.oneUdi = string1
                let str = oneStr
                // 找到第二个括号的位置
                const secondParenIdx = str.indexOf('(', str.indexOf('(') + 1)
                console.log(secondParenIdx)
                if (secondParenIdx !== -1) {
                  // 截取从第二个括号前面的内容
                  str = str.substring(secondParenIdx)
                }
                console.log('字符串2:', str)
                this.notOneUdi = str
              }
            }
          } else {
            console.log('不合规的条码')
          }
        }
      }
    },

    async edit(record) {
      let that = this
      try {
        const params = { id: record.id }
        const r = await queryYkCodeDetail(params)
        this.model = r.result
        // this.udiError = r.result.udi.includes('error') || r.result.udi == '' ? false : true
        this.$nextTick(() => {
          if (that.model.picUpload == null) {
            that.imgSrc = window._CONFIG.domianURL + 'sys/common/static/pandian/' + that.model.bar + '.jpg'
          } else {
            that.imgSrc = window._CONFIG.domianURL + 'sys/common/static/pandian/' + that.model.picUpload + '.jpg'
          }
        })
        // const dateTimeString = r.result.manufacture
        // const date = new Date(dateTimeString)

        // const formattedDate = `${date.getUTCFullYear().toString().slice(-2)}${(date.getUTCMonth() + 1)
        //   .toString()
        //   .padStart(2, '0')}${date.getUTCDate().toString().padStart(2, '0')}`

        // this.model.manufacture = formattedDate
      } catch (_) {}
      this.visible = true
    },
    submitForm() {
      const that = this
      if (!this.isSubmit) {
        this.$message.warning(this.errorText)
        retrun
      }
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(valid)
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
  watch: {
    notOneUdi(newVal, oldVal) {
      let _this = this
      if (newVal != oldVal && newVal != '') {
        let arr = newVal.split('(')

        console.log('-----------开始查询---', newVal)

        for (var i = 0; i < arr.length; i++) {
          let ele = arr[i]
          if (ele !== '') {
            // console.log('hhhh',ele2.substring(0,2))
            // return
            var flag2 = ele.substring(0, 2)
            console.log('flag2:' + flag2)
            if (flag2 === '17') {
              _this.model.validity = ele.substring(3)
            }
            if (flag2 === '10') {
              _this.model.batch = ele.substring(3)
            }
            if (flag2 === '11') {
              _this.model.manufacture = ele.substring(3)
            }
            if (flag2 === '91') {
              _this.model.serialNumberA = ele.substring(3)
            }
            if (flag2 === '21') {
              _this.model.serialNumberB = ele.substring(3)
            }
          }
        }
      }
    },
  },
}
</script>

<style scoped lang="scss">
.modal {
  display: block;
  position: fixed;
  z-index: 9999;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
}

.modal img {
  display: block;
  margin: 50px auto;
  max-width: 90%;
  max-height: 90%;
}

.close {
  position: absolute;
  top: 20px;
  right: 30px;
  color: #fff;
  font-size: 30px;
  font-weight: bold;
  cursor: pointer;
}

.ant-input-disabled {
  background-color: #fff;
  color: rgba(0, 0, 0, 0.65);
}
</style>

